let shoplist = document.getElementById("shoplist");
let btn = document.getElementById("btn");
let draggle = document.querySelector(".draggle");

let token = localStorage.getItem("token");
let host = "http://127.0.0.1:1337";

let user = document.querySelector(".order-head-right .user");
// 获取用户名
let uinfoUrl = host + "/api/v1/user/info";
// 头部设置token参数
axios.defaults.headers.common["token"] = token;
let uname = axios.get(uinfoUrl);

uname.then(function(res) {
    let userName = res.data.data.userName;
    user.innerHTML = userName;
})

// 分类id
let category = new URLSearchParams(location.search).get("id");

let data = {category};

let shopdetailUrl = host + "/api/v1/products";
let p1 = axios.get(shopdetailUrl,{params:data});

p1.then(function(res) {
    console.log(res.data.data);
    let shopdetArr = res.data.data;
    let shopdetStr = shopdetArr.map(item=> {
       console.log(item.coverImage.split("/")[1]);
       if(item.coverImage.split("/")[1]=="uploads") {
            item.coverImage = host+item.coverImage;
       } 
        return   ` 
            <li >
            <img src="${item.coverImage}" alt="${item.category.name}" pro_id="${item.id}">
            <p>${item.name}</p> 
            <div class="detail">${item.desc}</div>
            <div class="price">价格
                <span>${item.price}</span>元
                <span>起</span>
            </div>
            <div class="count">库存<span>${item.amount}</span></div> 
            <div class="mask" onclick="addcar(${item.id})">加入购物车</div>
            </li>
        ` 
    }).join("");
     shoplist.innerHTML = shopdetStr;
     let imgs = document.querySelectorAll("li img");
     imgs.forEach(img=> {
         img.onclick = function() {
            let pro_id = this.getAttribute("pro_id");
            let cover = this.src;
            console.log(pro_id);
            location.href = `comment.html?id=${pro_id}&coverImg=${cover}`;
         }
     })
})


function addcar(product) {
    if(token==null) {
        alert("请先登录哦!亲");
        location.href = "login.html";
        return;
    }
    draggle.style.opacity = 1;
    btn.setAttribute("data-id",product);
}

btn.onclick = async function() {
    draggle.style.opacity = 0;
    let product = Number(this.getAttribute("data-id"));
    let amount = Number(this.previousElementSibling.value);
    let caraddUrl = host + "/api/v1/shop_carts";
    let addData = {product,amount};
    // 头部设置token参数
    axios.defaults.headers.common["token"] = token;
    let p2add =await axios.post(caraddUrl,addData);
}







